var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,
    operationList = [],
    $ = layui.jquery,
    laydate = layui.laydate,
    colorpicker = layui.colorpicker,
    customerName = getQueryVariable("customerName");


function getAllJson(jsons) {
    let tmpitem=[]
    if(isEmpty(customerName)){
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if (item["code"] === user.code) {
                tmparr["selected"] = true;
            }
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   this.getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
    }else {
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            tmparr["selected"]=true;
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   this.getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
    }

    return tmpitem
}

function getxmselect(el, name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


let  isMsn="否";
layui.use(['dropdown'], function () {
    var dropdown = layui.dropdown;
    dropdown.onFilter("printfn", function (event) {

        var checkStatus = table.checkStatus("offertableid");
        $.ajax({
            url: 'offer/getImgLogoUrl?id='+checkStatus.data[0].id,
            type: 'GET',
            async: false, // 同步
            success: function (date) {

            },
        });

        switch (event) {
            case "offerReportDomestic":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个报价单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的报价单据! ");
                    break;
                }

                window.open("views/jsp/report.jsp?ym=offerReportDomestic&code=code:"+checkStatus.data[0].id)
                break
            case "offerReport":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个报价单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的报价单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=offerReport&code=code:"+checkStatus.data[0].id)
                break
        }
    });
})


lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

let operationNoList = [];
let salesmanCodeList = [];
let deptOperationList=[];
let deptSalesmanList=[];
layer.ready(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    let userTree = [];
    if(treeList && treeList.list){
        userTree = getAllJson(treeList.list);
    }else {
        userTree = getAllJson([{name: user.name, code: user.code}]);
    }
    operationNoList = getxmselect("#operationNo","operationNo", userTree);
    salesmanCodeList = getxmselect("#salesmanCode","salesmanCode", userTree);

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })
    //获取所有公司信息
    $.ajax({
        url:"receivePayment/getCompanyInfo",
        async: false,
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    //公司名称
                    $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });

    let operationCodes = operationNoList.getValue("value").join();
    let salesmanCodes = salesmanCodeList.getValue("value").join();
    if(user.code === "admin"){
        operationCodes = "admin";
        salesmanCodes = "admin";
    }
    let obj = {operationNo : operationCodes, salesmanCode : salesmanCodes};
    if(!isEmpty(customerName)){
        let name = decodeURI(customerName);
        $("#billNo").val(name);
        obj = {operationNo : operationCodes, salesmanCode : salesmanCodes, billNo : name};
    }
    initTable(obj);
    table.on('sort(offertable)', function(item) {
        table.reload("#offerselect",{data:layui.table.cache.offertableid})
        setColor(layui.table.cache.offertableid);
        layui.table.cache.offertableid.map((item,index)=>{
            if (item.markColor) {
                $("[lay-id=offertableid] table tr:eq(" + (index + 1) + ")").css({ "background": item.markColor, "color": "white" })
            }
        })
    })
});
form.render();//表单刷新

function initTable(obj){
    table.render({
        elem: '#offerselect'
        ,where:obj
        ,url:'offer/getListByPage'
        ,toolbar: '#offertoolbar'
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'statusStr', title:'单据类型', width: 120}
            ,{field:'billNo', title:'报价单号',sort:true,width: 240,event: "quotationno"}
            ,{field:'time', title:'报价日期',sort:true,width: 120}
            ,{field:'customerName', title:'客户名称',sort:true,width: 240}
            ,{field:'countryName', title:'国家',sort:true,width: 120}
            ,{field:'customerContactName', title:'客户联系人',sort:true,width: 120}
            ,{field:'contactEmail', title:'联系人邮箱',sort:true,width: 240}
            ,{field:'termOfValidity', title:'报价有效期限',sort:true,width: 120}
            ,{field:'deliveryPeriod', title:'交货期限',sort:true,width: 120}
            ,{field:'priceTermsName', title:'价格术语',sort:true,width: 240}
            ,{field:'totalQuotation', title:'报价总额',sort:true,width: 120}
            ,{field:'salesman', title:'业务员',sort:true,width: 120}
            ,{field:'signingCompanyName',title:'签约公司',sort:true,width: 250}
            ,{field:'memo', title:'备注', width: 220}
            // ,{fixed: 'right', width:240, toolbar: '#offereditor', title:'操作'}
            ,{fixed: 'right', width:300, title:'操作',templet: function(d){
                    // 单据状态/类型（1：草稿箱，2：待批箱，3：已批箱，4：完成箱，5垃圾箱）
                    let html="<div>"
                    if(isMsn=="是"){//管理员
                        if(d.status==1 || d.status==2){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                        }
                        if(d.status==1){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if(d.status==2){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                        }
                        if(d.status==2 || d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        }
                        if(d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                            if (user.code === "RKB005") {
                                html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                            }
                        }
                        if (d.status == 4 && user.code === "RKB005") {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"completeBack\">完成退回</a>"
                        }
                        if(d.status==5){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">彻底删除</a>"
                        }
                    }else {
                        if (d.status == 1) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if (d.status == 2) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        }
                        if(d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        if(d.status==5){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">彻底删除</a>"
                        }
                    }
                    if (d.status == 1 || d.status == 2 || d.status == 3 || d.status == 4) {
                        html = html + '<small>标记：</small> <div class="colorvalue" data-id = "'+d.id+'" data-index="'+d.LAY_TABLE_INDEX+'"></div>'
                    }
                    return html + "</div>";
                }}
        ]]
        ,id: 'offertableid'
        ,height: $(document).height() - $('#offerselect').offset().top - 75
        ,page: true
        ,limit: 50
        ,limits: [50, 100, 200, 300, 500]
        ,done(res, curr, count) {
            setColor(res.data);
        }
    });
}

function setColor(data) {
    lay('.colorvalue').each(function () {
        let xb = $(this).attr("data-id");
        let colors = "";
        for (var i = 0; i < data.length; i++) {
            if (data[i].id == xb && typeof (data[i].markColor) != "undefined" && data[i].markColor != "") {
                Layui_SetDataTableRowColor('tablediv', $(this).attr("data-index"), data[i].markColor);
                colors = data[i].markColor;
            }
        }
        let that = this
        colorpicker.render({
            elem: this //绑定元素
            , color: colors //设置默认色
            , predefine: true
            , done: function (color) {//点击颜色选择器的“确认”和“清除”按钮，均会触发 done 回调，回调返回当前选择的色值

                // Layui_SetDataTableRowColor('tablediv', index, color);
                //保存修改的颜色
                let id = $(this.elem).attr("data-id");
                let i
                data.map((item,index)=>{
                    if(item.id==id){
                        i=index
                    }
                })
                Layui_SetDataTableRowColor('tablediv', i, color);
                let req = {
                    id: id,
                    color: color
                }
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: 'application/json',
                    data: JSON.stringify(req),
                    url: "offer/updateMarkColor",
                    success: function (data) {
                        if (data.status == 200) {
                            layer.msg('修改成功');
                        } else {
                            layer.msg(data.msg);
                        }
                    }
                });
            }

        });
    });
}

//设置layui datatable的某一行的颜色
//DivId:datatable父div的 id;RowIndex:行序列号；Color：颜色字符串，如'#FF3030'
function Layui_SetDataTableRowColor(DivId, RowIndex, Color) {
    try {
        let div = document.getElementById(DivId);
        if (div != null) //找到对象了
        {
            let table_main = div.getElementsByClassName('layui-table-main');   //通过class获取table_main
            if (table_main != null && table_main.length > 0) {
                let table = table_main[0].getElementsByClassName('layui-table');   //通过class获取table
                if (table != null && table.length > 0) {
                    let trs = table[0].querySelectorAll("tr");
                    if (trs != null && trs.length > 0) {
                        trs[RowIndex].style.backgroundColor = Color;//背景颜色
                    }
                }
            }

        }
    } catch (e) {
        console.log(e.message);
    }
}

table.on('tool(offertable)', function(obj){
    let data = obj.data;
    let id = data.id;
    if(obj.event === 'update') {
        parent.intab("views/jsp/ExportBusiness/tpl/updateOffer.jsp?id="+obj.data.id,"修改报价")
    }else if(obj.event === 'delect'){
        layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
            layer.close(index);
            let dataBases={
                id:id,
                status:data.status
            }
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(dataBases),
                url:"offer/delete",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("删除成功", {icon: 6});
                        table.reload('offertableid', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            ,where: data.field
                        }, 'data');
                        return false;
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', confirmInfo(3, 5), function (index) {
            // startPurchaseProcess(id);
            operationData(data, 1, "提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', confirmInfo(3, 5), function (index) {
            operationData(data, 2, "审批通过");
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', confirmInfo(3, 5), function (index) {
            operationData(data, 3, "审批退回");
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', confirmInfo(3, 5), function (index) {
            operationData(data, 4, "完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', confirmInfo(3, 5), function (index) {
            operationData(data, 5, "还原");
        });
    }else if(obj.event === 'completeBack'){
        layer.confirm('确定完成退回吗', confirmInfo(3, 5), function (index) {
            operationData(data, 2, "完成退回");
        });
    }else if (obj.event === "quotationno"){
        parent.intab("views/jsp/ExportBusiness/tpl/viewoffer.jsp?id="+obj.data.id,"报价明细")
    }
});

//审批流开始，获取流程ID
function startPurchaseProcess(bid) {
    let res;
    $.ajax({
        type : 'get',
        data:{"processDefId":'offer',"bid":bid,"variables":null},
        url:'process/startProcess',
        dataType:"json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}

function operationData(data, operation, msg){
    let fields = {
        id : data.id,
        billNo : data.billNo,
        operation: operation
    }
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"offer/operation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('offertableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

function getCodeList(){
    let userCode = "";
    for(let i in operationList){
        if(isEmpty(userCode)){
            userCode = userCode + operationList[i].code;
        }else{
            userCode = userCode + "," + operationList[i].code;
        }
    }
    return userCode;
}
form.on('submit(submitform)', function(data){
    initTable(data.field);
    return false;
});

table.on('toolbar(offertable)', function(obj){
    let checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/newupoffer.jsp","新增报价")
            break;
        case 'copys':
            let data = checkStatus.data;
            if(data.length == 1){
                parent.intab("views/jsp/ExportBusiness/tpl/copyOffer.jsp?id="+data[0].id,"复制报价");
            }else{
                layer.msg("复制报价请选取一个数据进行操作")
            }
            break;
        case 'dayin':
            if(checkStatus.data.length > 1){
                layer.msg( "每次只能打印一个报价单据! ");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印的报价单据! ");
                break;
            }
            window.open("views/jsp/report.jsp?ym=offerReport&code=code:"+checkStatus.data[0].id)
            break;
        case 'checkSubmit':
            batchOperation(checkStatus.data, "一键提交成功！", 1);
            break;
        case 'checkAdopt':
            batchOperation(checkStatus.data, "一键通过成功！", 2);
            break;
    };
});

//一键操作
function batchOperation(data, msg, type){
    if(data.length == 0){
        layer.msg("请选择数据！", {icon: 5});
        return;
    }
    let fields = {};
    fields["type"] = type;
    fields["operationReqs"] = data;
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"offer/batchOperation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('offertableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

$("#statistical").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/offerStatistics.jsp","报价统计")
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}


function downLogo(url){
    $.ajax({
        url: 'ftp/onLine2?pathString='+url,
        type: 'GET',
        async: false, // 同步
        success: function (date) {

        },
        error:function (date) {

        }
    });
}

document.getElementById('clear').onclick = function(){
    operationNoList.setValue([ ]);
    salesmanCodeList.setValue([ ]);
    deptOperationList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
};
